<?php
/**
 * Created by PhpStorm.
 * User: refar
 * Date: 21-7-20
 * Time: 下午4:20
 */

namespace app\v2\controller;

use think\Controller;
use think\Cookie;
use think\Response;
use think\Request;
use think\exception\HttpResponseException;

use think\Log;
use think\Exception;
use think\Db;

class Common extends Controller {

    //登录用户
    public $loginUser = array();
    // 是否有显示隐藏项目
    public $showVisible = false;

    public function _initialize(){
        parent::_initialize();
        $this->checkMethod();
        $this->checkCookie();
    }

    public function checkMethod() {
        // vue会发送预请求, option处理
        if (Request::instance()->isOptions()) {
            $result = [
                'status' => SUCCESS,
                'msg'  => 'P.G.D', // permission get data
                'data' => []
            ];

            $this->throwJsonException($result);
        }
    }

    public function checkCookie(){
        if (config('session_debug')) {
            // 读取配置文件
            $roleFile = RUNTIME_PATH. 'roleId.txt';
            if (file_exists($roleFile)) {
                $roleArray = explode("&", file_get_contents($roleFile));
                $this->loginUser = array('T'=>'admin', 'roleId'=>$roleArray[0], 'depart'=>$roleArray[1],
                    'email'=>'world.hello@dbh.dynabook.com', 'name'=>'芜湖', 'desc'=>'拯救世界的直男');
                if($roleArray[0] == SALE_ADMIN) {
                    $this->showVisible = true;
                }
            } else {
                $this->loginUser = array('T'=>'admin', 'roleId'=>PSO, 'depart'=>'总经办',
                    'email'=>'world.hello@dbh.dynabook.com', 'name'=>'芜湖', 'desc'=>'拯救世界的直男');
            }

        } else {
            if (null == $this->request->server('HTTP_REFERER')) {
                $result = [
                    'status' => ERROR,
                    'msg'  => 'no http referer',
                    'data' => []
                ];
                $this->throwJsonException($result);
            } else {
                try {
                    $userCookie = Cookie::get('TESTLINK_USER_AUTH_COOKIE');
                    if (null == $userCookie) {
                        $result = [
                            'status' => TIMEOUT,
                            'msg'  => 'user session timeout',
                            'data' => []
                        ];
                        $this->throwJsonException($result);
                    }
                    // 查看T系统用户的权限 (查询right_id)
                    $t_user = Db::table('users')->where('cookie_string', $userCookie)->alias('a')
                        ->join('role_rights b', 'a.role_id=b.role_id', 'LEFT')
                        ->find();
                    if (null == $t_user['right_id']) {
                        // 像预留角色之类, 会被拒绝登录
                        $result = [
                            'status' => ERROR,
                            'msg'  => 'T reject',
                            'data' => []
                        ];
                        $this->throwJsonException($result);
                    } else {
                        // 查询role-desc给log_record用
                        $role = Db::table('roles')->field('notes')
                            ->where('id', $t_user['role_id'])->find();
                        $desc = str_replace('</p>', '',
                            str_replace('<p>', '', (empty($role['notes']) ? '': $role['notes'])));

                        $this->loginUser = array(
                            'T'=>$t_user['login'],
                            'roleId'=>$t_user['role_id'],
                            'depart'=>$t_user['department'],
                            'email'=>$t_user['email'],
                            'name'=>$t_user['last']. $t_user['first'],
                            'desc'=>$desc,
                        );
                        if ($t_user['role_id'] == ROLE_DATA_VISIBLE) {
                            $this->showVisible = true;
                        }

                        Log::record('hello! ['. $desc . '] ' . $t_user['login']);
                    }

                } catch (Exception $e) {
                    Log::record('[Common][checkCookie] error '. $e->getMessage());
                    $result = [
                        'status' => ERROR,
                        'msg'  => 'server error',
                        'data' => []
                    ];
                    $this->throwJsonException($result);
                }
            }

        }
    }

    // 可能每个继承类都需要查询userInfo
    protected function getUserInfoById($userId) {

        try {
            $user = Db::table('users')->where('login', $userId)->where('active', 1)->find();
            return $user;
        } catch (Exception $e) {
            Log::record('[Common][getUserInfoById] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
    }

    protected function getDepartV2() {
        try {
            $res = Db::table('trc_group')->distinct(true)->field('depart_desc')
                ->where('is_sale', 1)->select();
            $depart = [];
            foreach ($res as $item) {
                $depart[] = $item['depart_desc'];

            }
            return $depart;
        } catch (Exception $e) {
            Log::record('[Common][getDepartV2] error' . $e->getMessage());
            return apiResponse(ERROR, ' server error');
        }

    }

    protected function getSectionsV2() {
        try {
            $res = Db::table('trc_group')->distinct(true)->field('section_desc')
                ->where('is_sale', 1)->select();
            $section = [];
            foreach ($res as $item) {
                $section[] = $item['section_desc'];

            }
            return $section;
        } catch (Exception $e) {
            Log::record('[Common][getSectionsV2] error' . $e->getMessage());
            return apiResponse(ERROR, ' server error');
        }

    }

    private function throwJsonException($result) {
        $response = Response::create($result, $this->getResponseType())->header(getHttpHeader());
        throw new HttpResponseException($response);
    }
}